﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using Rabbit.Modal;
using Rabbit.Utils;
using Rabbit.BusinessLogicLayer;

namespace MicroBlogClient
{
    /// <summary>
    /// Interaction logic for LoginWindow.xaml
    /// </summary>
    public partial class LoginWindow : Window
    {
        DispatcherTimer timerOpenAuthenticationUrl = new DispatcherTimer();
        private string AuthenticationUrl;
        Properties.Settings settings = new Properties.Settings();

        public string strUserLableText
        {
            get { return (string)GetValue(strUserLableTextProperty); }
            set { SetValue(strUserLableTextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for strUserLableText.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty strUserLableTextProperty =
            DependencyProperty.Register("strUserLableText", typeof(string), typeof(LoginWindow), new UIPropertyMetadata("用户"));

        public LoginWindow()
        {
            InitializeComponent();
            LoadUserList();
            DataContext = this;

            RequestHelper.SetOAuthBaseUrl(
              Application.Current.Resources["RequestTokenUrl"].ToString(),
              Application.Current.Resources["AuthorizationTokenUrl"].ToString(),
              Application.Current.Resources["AccessTokenUrl"].ToString(),
              Application.Current.Resources["ConsumerKey"].ToString(),
              Application.Current.Resources["ConsumerSecret"].ToString(),
              Application.Current.Resources["APIBaseUrl"].ToString()
            );
        }

        private void LoadUserList()
        {
            try
            {
                if (settings.UserList == null)
                {
                    settings.UserList = new UserList();
                }
                List<UserSettings> userList = settings.UserList.FindAll(u => u.IsVisibleOnLoginWindow.Value == true);
                userList.Sort();
                cmbUserList.ItemsSource = userList;
                settings.Save();
            }
            catch (Exception ex)
            {
                LogHelper.LogError(ex);
                try
                {
                    System.IO.File.Delete((ex.InnerException as System.Configuration.ConfigurationException).Filename);
                    settings.Reload();
                    settings.Save();
                }
                catch (Exception)
                {
                }
            }
        }

        #region TitleBarButton Click Event
        private void btnTitleBarMin_Click(object sender, RoutedEventArgs e)
        {
            this.ShowInTaskbar = true;
            this.WindowState = System.Windows.WindowState.Minimized;
        }

        private void btnTitleBarClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        #endregion

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            if (cmbUserList.SelectedValue == null && chkNewUser.IsChecked == false)
            {
                return;
            }
            else if (chkNewUser.IsChecked == true && string.IsNullOrEmpty(txtVerifyCode.Text))
            {
                return;
            }

            btnLogin.IsEnabled = false;

            bool IsNewUser = chkNewUser.IsChecked.Value;
            string verifyCode = txtVerifyCode.Text;
            long selectedUserID = IsNewUser ? 0 : long.Parse(cmbUserList.SelectedValue.ToString());
            bool IsRememberMe = chkRememberme.IsChecked.Value;
            Action generateAccessToken = new Action(() =>
                {
                    try
                    {
                        if (IsNewUser == true)
                        {
                            RequestHelper.GenerateAccessToken(verifyCode);
                        }
                        else
                        {
                            UserSettings token = settings.UserList.Find(u => u.UserID == selectedUserID);
                            RequestHelper.SetAccessToken(token);
                        }

                        UserBL.GetCurrentUserInformation();

                        if (settings.UserList == null)
                        {
                            settings.UserList = new UserList();
                            settings.Save();
                        }

                        int settingsLocation = settings.UserList.FindIndex(u => u.UserID == UserBL.CurrentUser.Id);
                        UserSettings userSettings;
                        if (settingsLocation != -1)
                        {
                            userSettings = settings.UserList[settingsLocation];

                            //check UserSetting's field, and compare it's value with current saved userSetting
                            //if the value of current userSetting is null, set its default value to be the the default value of UserSetting class
                            Type UserSettingsType = typeof(UserSettings);
                            var properties = UserSettingsType.GetProperties();
                            foreach (var property in properties)
                            {
                                string propertyName = property.Name;
                                if (UserSettingsType.GetProperty(propertyName).GetValue(userSettings, null) == null)
                                {
                                    UserSettingsType.GetProperty(propertyName).SetValue(userSettings, settings[propertyName], null);
                                }
                            }
                            userSettings.LastAccessTime = DateTime.Now;
                            userSettings.IsVisibleOnLoginWindow = IsRememberMe;

                            settings.UserList[settingsLocation] = userSettings;
                        }
                        else
                        {
                            //load default settings from user.config
                            userSettings = new UserSettings()
                            {
                                LastAccessTime = DateTime.Now,
                                UserName = UserBL.CurrentUser.ScreenName,
                                PopupForMetionedMe = settings.PopupForMetionedMe,
                                PopupForNewComment = settings.PopupForNewComment,
                                PopupForNewStatus = settings.PopupForNewStatus,
                                Theme = settings.Theme,
                                HelpPublicizing = settings.HelpPublicizing,
                                UpdateInterval = settings.UpdateInterval,
                                IsVisibleOnLoginWindow = IsRememberMe,
                                UserID = UserBL.CurrentUser.Id,
                                TokenID = RequestHelper.AccessToken,
                                TokenSecret = RequestHelper.AccessTokenSecret,
                                MainWindowOpacity = settings.MainWindowOpacity,
                                MainWindowBackgroundOpacity = settings.MainWindowBackgroundOpacity,
                                PopupMessageShowTime = settings.PopupMessageShowTime,
                                IsTwinkleSysTrayIcon = settings.IsTwinkleSysTrayIcon,
                                CaptureScreenHotKey = settings.CaptureScreenHotKey,
                                GetCommentHotKey = settings.GetCommentHotKey,
                                GetLetterHotKey = settings.GetLetterHotKey,
                                GetStatusHotKey = settings.GetStatusHotKey,
                                GetMetionedMeHotKey = settings.GetMetionedMeHotKey,
                                IsPlayingSound = settings.IsPlayingSound,
                                PopupForNewLetter = settings.PopupForNewLetter
                            };
                            settings.UserList.Add(userSettings);
                        }

                        UserBL.CurrentUser.UserSettings = userSettings;
                        settings.Save();
                    }
                    catch (MaxRatesExceededException ex)
                    {
                        MessageBox.Show("超过最大次数访问上限,暂时无法使用该软件。\r\n该限制将在" + ex.RatesInformation.ResetTime + "后自动解除");
                        return;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("登录失败,错误信息：" + ex.Message);
                        return;
                    }
                    finally
                    {
                        this.Dispatcher.BeginInvoke(new Action(() => btnLogin.IsEnabled = true));
                    }

                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        if (UserBL.CurrentUser != null)
                        {
                            //load default theme
                            App.Current.Resources.MergedDictionaries.Clear();
                            App.Current.Resources.MergedDictionaries.Add(Rabbit.Themes.ThemeManager.GetTheme(UserBL.CurrentUser.UserSettings.Theme));

                            OpenMainWindow();
                        }
                    }));
                });

            generateAccessToken.BeginInvoke(null,null);
        }
        private void OpenMainWindow()
        {
            contentProcessingImage.SetValue(ContentControl.ContentProperty, null);
            MainWindow mainWindow = new MainWindow();
            mainWindow.WindowState = System.Windows.WindowState.Normal;
            Application.Current.MainWindow = mainWindow;
            mainWindow.Show();
            mainWindow.Activate();
            this.Hide();
        }
        private void btnDeleteMe_Click(object sender, RoutedEventArgs e)
        {
            long deleteUserID = long.Parse((sender as Button).CommandParameter.ToString());
            settings.UserList.RemoveAll(u => u.UserID == deleteUserID);
            settings.Save();
            cmbUserList.ItemsSource = settings.UserList;
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Window_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.Source is Canvas || e.Source is TextBlock)
            {
                base.DragMove();
            }
        }

        private void chkNewUser_Click(object sender, RoutedEventArgs e)
        {
            strUserLableText = chkNewUser.IsChecked == true ? "验证码" : "用户";
            if (chkNewUser.IsChecked == true)
            {
                txtVerifyCode.Focus();
                popupUserTips.IsOpen = true;
                Action tempDelegate = new Action(() =>
                    {
                        try
                        {
                            AuthenticationUrl = RequestHelper.GetAuthorizationUrl();

                            this.Dispatcher.BeginInvoke(new Action(() =>
                            {
                                timerOpenAuthenticationUrl = new DispatcherTimer();
                                timerOpenAuthenticationUrl.Interval = TimeSpan.FromSeconds(3);
                                timerOpenAuthenticationUrl.Tick += new EventHandler((obj, args) =>
                                {
                                    Process.Start(AuthenticationUrl);
                                    timerOpenAuthenticationUrl.Stop();
                                });
                                timerOpenAuthenticationUrl.Start();
                            }
                            ));
                        }
                        catch (Exception ex)
                        {
                            LogHelper.LogError(ex);
                            MessageBox.Show("无法连接到搜狐微博，请稍后重试");
                        }
                    }
                    );
                tempDelegate.BeginInvoke(null, null);
            }
            else
            {
                timerOpenAuthenticationUrl.Stop();
            }

            this.Topmost = (bool)chkNewUser.IsChecked;
        }

        private void linkOpenImmediately_Click(object sender, RoutedEventArgs e)
        {
            Process.Start(AuthenticationUrl);
            timerOpenAuthenticationUrl.Stop();
        }
    }
}
